package com.boot.utils;

import java.util.*;

/**
 * 安全密码生成器：生成包含大小写字母、数字、特殊符号的 12 位强密码
 */
public class PasswordGenerator {

    private static final String LOWER = "abcdefghijklmnopqrstuvwxyz";
    private static final String UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String DIGITS = "0123456789";
    private static final String SPECIAL = "!@#$%^&*";

    private static final Random RANDOM = new Random();

    /**
     * 生成一个 12 位的安全密码，确保至少包含：
     * - 1 个大写字母
     * - 1 个小写字母
     * - 1 个数字
     * - 1 个特殊符号
     * 剩余字符从所有字符集中随机选择
     */
    public static String generateSecurePassword() {
        StringBuilder password = new StringBuilder(12);

        // 确保每类至少有一个字符
        password.append(LOWER.charAt(RANDOM.nextInt(LOWER.length())));
        password.append(UPPER.charAt(RANDOM.nextInt(UPPER.length())));
        password.append(DIGITS.charAt(RANDOM.nextInt(DIGITS.length())));
        password.append(SPECIAL.charAt(RANDOM.nextInt(SPECIAL.length())));

        // 剩下 8 个字符从所有字符中随机选取
        String allChars = LOWER + UPPER + DIGITS + SPECIAL;
        for (int i = 0; i < 8; i++) {
            password.append(allChars.charAt(RANDOM.nextInt(allChars.length())));
        }

        // 打乱顺序，避免前四位是固定的类型
        List<Character> chars = new ArrayList<>();
        for (char c : password.toString().toCharArray()) {
            chars.add(c);
        }
        Collections.shuffle(chars);

        StringBuilder shuffled = new StringBuilder();
        for (Character ch : chars) {
            shuffled.append(ch);
        }

        return shuffled.toString();
    }
}
